<template>
    <div style="margin-top: 5%">
        <el-card>
            <div slot="header">
                <span>小说详情</span>
            </div>
            <div style="display: flex; align-items: center; justify-content: space-between;">
                <div>
                    <p><strong>书名：</strong>{{ novel.title }}</p>
                    <p><strong>作者：</strong>{{ novel.author }}</p>
                    <p><strong>类型：</strong>{{ novel.type }}</p>
                    <p><strong>简介：</strong>{{ novel.intro }}</p>
                    <p><strong>更新时间：</strong>{{ novel.updateTime }}</p>
                    <el-button v-if="exist" type="danger" @click="yichu(novel)">移除书架</el-button>
                    <el-button v-else type="primary" @click="SetShujia(novel)">加入书架</el-button>
                </div>
                <div>
                    <img :src="novel.imgUrl" :alt="novel.title" style="width: 110px; height: 130px;">
                </div>
            </div>
        </el-card>

        <el-card style="width: 60%;margin-left: 20%;margin-top: 3%">
            <div slot="header">
                <span>目录</span>
            </div>
            <div class="chapter-container">
                <div v-for="(item, index) in novel.chapter" :key="index" class="chapter-item">
                    <a @click="getNovel(item)"><strong>{{ item.chapter }}</strong></a>
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
export default {
    name: "details",
    data() {
        return {
            novel: {},  // 初始化为空对象
            exist: true
        }
    },
    mounted() {
        if (this.$route.query && this.$route.query.row) {
            this.novel = JSON.parse(this.$route.query.row);
        } else {
            console.error('未找到小说数据');
        }

        this.$request.get('/novels/shujia/exist?id=' + this.novel.id).then(res => {
            this.exist = res
        })
    },
    methods: {
        getNovel(item) {
            localStorage.setItem('novel', JSON.stringify(item))
            this.$router.push('/neirong')
        },
        SetShujia(novel) {
            let shujia = {shuId: novel.id, type: novel.type}
            this.$request.post('/novels/shujia', shujia).then(res => {
                this.$message.success("添加成功")
                this.exist = true
            })
        },
        yichu(novel) {
            this.$request.delete("/novels/shujia", {params: {id: novel.id}}).then(res => {
                this.$message.success("移除成功")
                this.exist = false
            })
        }
    }
}
</script>

<style scoped>
.chapter-container {
    display: flex;
    flex-wrap: wrap; /* 允许换行 */
}

.chapter-item {
    width: 33.33%; /* 三等分来显示，每行三个 */
    box-sizing: border-box;
    padding: 10px;
}

/* 示例中的其他样式 */
</style>